<?php

namespace app\api\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;

class ExceptionHandler extends Handle
{
    public $state       = 0;
    public $msg         = "服务器异常";
    public $code        = 500;

    public function render(Exception $e)
    {
        // if (config('app_debug') == true) {
        //     return parent::render($e);
        // }

        //自定义异常
        if ($e instanceof BaseException) {
            $this->state = $e->state;
            $this->msg = $e->msg;
            $this->code = $e->code;
            return json(['state' => $this->state, 'msg' => $this->msg, 'code' => $this->code]);
        }

        // 参数验证错误
        if ($e instanceof \think\exception\ValidateException) {
            return json(['state' => 0, 'msg' => $e->getError(), 'code' => $this->code]);
        }

        // // 请求异常
        // if ($e instanceof \think\exception\HttpException || request()->isAjax()) {
        //     return json(['state' => 0, 'msg' => $e->getMessage(), 'code' => $this->code]);
        // }

        // //异常错误
        // if ($e instanceof \think\exception\ErrorException) {
        //     return json(['state' => 0, 'msg' => $e->getMessage(), 'code' => $this->code]);
        // }

        return json(['state' => $this->state, 'msg' => $e->getMessage(), 'code' => $this->code]);
    }
}
